package com.xp.agent.main;

import java.lang.management.ManagementFactory;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import com.xp.agent.common.CommonProperties;
import com.xp.agent.task.ConfigLoader;
import com.xp.agent.task.FileLogTask;
import com.xp.agent.task.GcTask;
import com.xp.agent.task.MemTask;
import com.xp.agent.task.ThreadTask;
import com.xp.hotswap.builder.HotswapBuilder;

public class MainThread implements Runnable {

	private static Executor pool = Executors.newCachedThreadPool();

	@Override
	public void run() {
		String config = "";
		List<String> inputArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
		for (String path : inputArguments) {
			if (path.contains("-javaagent")) {
				String replace = path.replace("\\", "/");
				config = replace.substring(replace.indexOf(":") + 1, replace.lastIndexOf("/") + 1);
				break;
			}
		}
		ConfigLoader configLoader = new ConfigLoader(config + CommonProperties.CONFIG_FILE_NAME);
		new HotswapBuilder().setCheckFileTime(3000L).setPlugFilePath(config).isGCToDelteFile(false).startHotswap();
		/*
		 * load config
		 */
		try {
			configLoader.loadFile();
		} catch (Exception e) {
		}
		/*
		 * reload config thread
		 */
		pool.execute(configLoader);
		/*
		 * gc thread
		 */
		pool.execute(new GcTask());
		/*
		 * file log thread
		 */
		pool.execute(new FileLogTask());
		/*
		 * thread task
		 */
		pool.execute(new ThreadTask());
		/*
		 * mem thread
		 */
		pool.execute(new MemTask());

	}

}
